<template>
  <view class="wrap">
    <uv-navbar :fixed="false" title="回答问题" safeAreaInsetTop placeholder :border='false'>
      <template v-slot:left>
        <view class="navEditName nav-left" @click="goBack">取消</view>
      </template>
      <template v-slot:right>
        <view class="navEditName nav-right" @click="tap">保存</view>
      </template>
    </uv-navbar>
    <view class="content">
      <uv-textarea v-model="base.content" placeholder="点击此处说点什么…" border='none' maxlength='-1' height="100%" placeholderStyle='font-weight: 400; font-size: 32rpx; color: #B8B8B8;' textStyle='font-weight: 400; font-size: 32rpx; color: #000000;' customStyle='height: 100%'></uv-textarea>
    </view>
    <uv-overlay :show="scoll" zIndex='998' opacity='0' @click="scoll = !scoll"></uv-overlay>
    <view class="footer">
      <view class="imgs" v-if="base.images.length">
        <view class="item" v-for="(item, index) in base.images" :key="index">
          <image :src="setUrl(item)" class="img" mode="aspectFill" @click="previewImage(item)"></image>
          <image src="../../../static/delete.png" class="delete" @click="imgClick(index)"></image>
        </view>
      </view>
      <view class="filed" v-if="base.files.length">
        <view class="files">
          <view class="call" v-for="(item, index) in base.files">
            <view class="flieIcon">{{ setUrl(item).substring(setUrl(item).lastIndexOf(".") + 1) }}</view>
            <view class="name">{{ setUrl(item) }}</view>
            <view class="delete" @click="fileClick"><image src="../../../static/delete.png" class="img"></image></view>
          </view>
        </view>
      </view>
      <view class="fasc">
        <view class="cell" @click="chooseImage">
          <image src="../../../static/uploadImage.png" class="img"></image>
        </view>
        <view class="cell" @click="chooseFile">
          <image src="../../../static/filed.png" class="img"></image>
        </view>
      </view>
      <view class="base" :class="{scoll: scoll}">
        <uv-safe-bottom></uv-safe-bottom>
      </view>
      <uv-safe-bottom></uv-safe-bottom>
    </view>
    <view class="safe"></view>
    <uv-safe-bottom></uv-safe-bottom>
    
    <uv-modal ref="modal" title="需要文件访问权限" showCancelButton confirmColor='#E43222' confirmText='去授权' @confirm="confirm">
      <view>
        您还未授权本应用读取文件。为保证您可以正常上传文件，请在权限设置页面打开文件访问权限（不同手机厂商表述可能略有差异）请根据自己手机品牌设置
      </view>
    </uv-modal>
    <uv-modal ref="storageModal" title="提示" showCancelButton confirmColor='#E43222' confirmText='保存' @cancel='cancel' @confirm="keyStorage">
      <view>
        是否保存草稿箱？
      </view>
    </uv-modal>
    
    <action ref="actionPhoto" :size="{ width: 200, height: 200 }" @click="getImageUrl"></action>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useOrder } from '@/store';
import { onShow, onUnload, onLoad } from "@dcloudio/uni-app";
import { post } from '@/api';
import { choose, toast, setUpload, setUrl } from '@/common';

// #ifdef APP-PLUS
const lemonjkFileSelect = uni.requireNativePlugin('lemonjk-FileSelect');
// #endif

const modal = ref(null);
const actionPhoto = ref(null);
const storageModal = ref(null);

let content = ref('');
let scoll = ref(false);
let base = ref({
  question_id: '',
  association_id: '',
  content: '',
  files: [],
  images: [],
})
let ros = '';

let body = computed(() => {
  const store = useOrder();
  return uni.$uv.deepClone(store.group);
});

onLoad((option) => {
  base.value.question_id = option.question_id;
  base.value.association_id = option.association_id;
  
  const issue = uni.getStorageSync('issue');
  if(issue){
    const val = uni.$uv.deepClone(issue);
    base.value.content = val.content ? val.content : '';
    base.value.files = (val.files && val.files.length) ? val.files : [];
    base.value.images = (val.images && val.images.length) ? val.images : [];
  }
})
onUnload(() => {
  console.log('页面卸载');
  uni.$off('update');
})

uni.$on('update',function(data){
  console.log("监听事件");
  const obj = data.msg;
  const index = talkSelect.value.findIndex(o => o.id == obj.id);
  if(index == -1){
    talkSelect.value = [...talkSelect.value, obj];
  }
})
// tab禁止点击多次
let debounce = false;
function tap(){
  if(debounce) return;
  debounce = true;
  console.log(base.value);
  const params = {};
  if(base.value.files.length){
    params.files = base.value.files.toString();
    params.type = 2;
  }else{
    params.files = '';
    params.type = 1;
  }
  if(base.value.images.length){
    params.images = base.value.images.toString();
  }else{
    params.images = '';
  }
  if(!base.value.content) return toast('请输入内容');
  params.content = base.value.content;
  params.question_id = base.value.question_id;
  params.association_id = base.value.association_id;
  console.log(params);
  post('api/association_answer/answerQuestion', params).then(res => {
    if(res.code == 1){
      toast('提交成功', true);
      uni.removeStorageSync('issue');
      setTimeout(() => {
        uni.redirectTo({
          url: `/pages/group/question/answerDetail?id=${base.value.question_id}`
        });
      }, 1000)
    }
  })
}
// 选择图片并上传
function chooseImage(){
  if(base.value.files.length) return toast('文件与图片不能一起上传');
  if(base.value.images.length >= 9) return toast('最多上传9张');
  ros = 'camera';
  
  actionPhoto.value.open();
}
function getImageUrl(url){
  base.value.images = [...base.value.images, url];
}
// 选择文件并上传
function chooseFile(){
  // #ifndef APP-PLUS
  return toast('请打开APP上传');

  // #endif
  ros = 'file';
  // #ifdef APP-PLUS
  if(base.value.images && base.value.images.length) return toast('文件与图片不能一起上传');
  lemonjkFileSelect.showPicker({
    mimeType: '*/*',
    utisType: 'public.data'
  }, res => {
    let os = uni.$uv.os();
    if(os == 'android'){
      if(res.code == 1001){
        modal.value.open();
      }else if(res.code == 0){
        setUpload([res.files[0].filePath]).then(file => {
          console.log(file);
          base.value.files = [...base.value.files, file];
        })
      }else{
        toast(res.detail)
      }
    }else{
      if(res.code == 0){
        setUpload([res.files[0].filePath]).then(file => {
          base.value.files = [...base.value.files, file];
        })
      }else{
        toast(res.detail)
      }
    }
  })
  // #endif
}
function confirm(){
  // 跳转到应用设置页
  lemonjkFileSelect.gotoSetting();  
}
// 图片预览
function previewImage(row){
  let picList = base.value.images.map(e => setUrl(e));
  uni.previewImage({
    current: setUrl(row),
    urls: picList,
  });
}
// 删除图片
function imgClick(index){
  base.value.images.splice(index, 1);
}
// 删除文件选择
function fileClick(index){
  base.value.files.splice(index, 1);
}
function goSearch(){
  uni.navigateTo({
    url: '/pages/group/searchTalk'
  });
}
function keyStorage(){
  uni.setStorageSync('issue', base.value);
  cancel();
}
function cancel(){
  storageModal.value.close();
  uni.removeStorageSync('issue');
  uni.navigateBack({
    delta: 1
  });
}
function goBack(){
  const value = base.value;
  if(value.content || value.files.length || value.images.length || value.talk_ids.length){
    storageModal.value.open();
  }else{
    cancel()
  }
}
</script>

<style lang="scss" scoped>
  .safe{
    width: 100%;
    height: 208rpx;
    background-color: #fff;
  }
  .footer{
    width: 100%;
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 999;
    border-top: 1px solid #F5F5F5;
    background-color: #fff;
    .tips{
      padding: 0 30rpx;
      padding-top: 20rpx;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .test{
        font-weight: 400;
        font-size: 32rpx;
        color: #465B89;
        margin-right: 20rpx;
      }
    }
    .filed{
      width: 100%;
      padding: 30rpx;
      .files{
        padding: 16rpx;
        background-color: #F5F5F5;
        .call{
          background-color: #FFFFFF;
          border-radius: 12rpx;
          // padding: 20rpx;
          padding-right: 20rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          margin-right: 12rpx;
          margin-bottom: 16rpx;
          &:last-child{
            margin-bottom: 0;
          }
          .flieIcon{
            width: 100rpx;
            height: 100rpx;
            padding: 10rpx;
            font-size: 30rpx;
            color: #FFFFFF;
            background-color: #E55D52;
            border-radius: 10rpx;
            margin-right: 10rpx;
            padding-bottom: 16rpx;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .delete{
            width: 24rpx;
            height: 24rpx;
            font-size: 0;
          }
          .name{
            font-weight: 400;
            font-size: 28rpx;
            color: #2B2B2B;
            width: 0;
            flex: 1;
            padding-right: 30rpx;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
    .imgs{
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      width: 100%;
      padding: 0 30rpx;
      padding-top: 20rpx;
      .item{
        width: 150rpx;
        height: 150rpx;
        margin-right: 20rpx;
        border-radius: 12rpx;
        margin-bottom: 20rpx;
        position: relative;
        .delete{
          width: 24rpx;
          height: 24rpx;
          position: absolute;
          right: -12rpx;
          top: -12rpx;
        }
      }
    }
    .addTopic{
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      padding-top: 36rpx;
      padding-bottom: 30rpx;
      border-top: 1px solid #E6E6E6;
      .font{
        font-weight: 400;
        font-size: 32rpx;
        color: #2B2B2B;
        padding-left: 12rpx;
      }
    }
    .base{
      transition: all .5s;
      max-height: 0;
      &.scoll{
        max-height: 1500rpx;
      }
    }
    .topic{
      padding: 0 30rpx;
      padding-bottom: 30rpx;
      .list{
        width: 100%;
        white-space: nowrap;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .item{
          font-weight: 400;
          font-size: 28rpx;
          color: #2B2B2B;
          padding: 0 24rpx;
          background-color: #F5F5F5;
          height: 64rpx;
          line-height: 64rpx;
          border-radius: 64rpx;
          margin-right: 24rpx;
          margin-bottom: 20rpx;
          text-align: center;
        }
      }
      .title{
        font-weight: 400;
        font-size: 28rpx;
        color: #999999;
        padding-bottom: 24rpx;
      }
    }
    .fasc{
      width: 100%;
      padding: 40rpx 30rpx;
      display: flex;
      align-items: center;
      .cell{
        margin-right: 50rpx;
        width: 40rpx;
        height: 40rpx;
      }
    }
  }
  .content{
    width: 100%;
    background-color: #fff;
    height: 45vh;
  }
  .navEditName{
    font-weight: 400;
    font-size: 28rpx;
    &.nav-left{
      color: #737373;
    }
    &.nav-right{
      color: #E43222;
    }
  }
</style>